import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken, removeRefreshToken } from '@/utils/auth'
import { setStore, getStore, removeStore } from '@/utils/store'
import resultCode from '@/utils/resultCode'

const user = {
  state: {
    account: null,
    status: '',
    code: '',
    token: getToken(),
    refresh_token: getRefreshToken(),
    name: '',
    avatar: '',
    introduction: '',
    menus: getStore({
      name: 'user.menus'
    }) || [], // 初始化菜单列表
    roles: [],
    permissions: [],
    setting: {
      articlePlatform: []
    }
  },

  mutations: {
    SET_CODE: (state, code) => {
      state.code = code
    },
    SET_TOKEN: (state, token) => {
      console.log('-------set token----' + token)
      state.token = token
      setToken(token)
      // setStore({
      //   name: 'user.token',
      //   content: token,
      //   type: 'session'
      // })
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      console.log('-------set refresh token----' + refreshToken)
      state.refresh_token = refreshToken
      setRefreshToken(refreshToken)
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_SETTING: (state, setting) => {
      state.setting = setting
    },
    SET_STATUS: (state, status) => {
      state.status = status
    },
    SET_INITMENU: (state, menus) => {
      state.menus = menus
      setStore({
        name: 'user.menus',
        content: menus,
        type: 'session'
      })
    },
    SET_ACCOUNT: (state, account) => {
      state.account = account
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 用户名登录
    LoginByUsername({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password).then(response => {
          const result = response.data
          if (result && result.code === resultCode.SUCCESS) {
            // 处理用户信息
            const data = result.data
            console.log('data:' + data)
            // 处理token
            commit('SET_TOKEN', data.access_token)
            commit('SET_REFRESH_TOKEN', data.refresh_token)
            // setToken(data.access_token)
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          if (!response.data) { // 由于mockjs 不支持自定义状态码只能这样hack
            reject('getUserInfo: error')
          }
          const result = response.data // 返回的业务json对象
          if (result && result.code === resultCode.SUCCESS) {
            const account = result.data
            console.log('-----------account---------')
            console.log(account)
            commit('SET_ACCOUNT', account)
            if (account.roles && account.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              console.log('account:' + account.roles)
              commit('SET_ROLES', account.roles)
            } else {
              reject('getInfo: roles must be a non-null array !')
            }
            if (account.permissions && account.permissions.length > 0) { // 验证返回的resources是否是一个非空数组
              commit('SET_PERMISSIONS', account.permissions)
            } else {
              console.log('account permissions:' + account.permissions)
              reject('getInfo: permissions must be a non-null array !')
            }
            commit('SET_NAME', account.accountName)
            commit('SET_AVATAR', account.headImg)
            commit('SET_INTRODUCTION', account.truename)
            resolve(response)
          } else {
            reject('getUserInfo: error')
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 第三方验证登录
    // LoginByThirdparty({ commit, state }, code) {
    //   return new Promise((resolve, reject) => {
    //     commit('SET_CODE', code)
    //     loginByThirdparty(state.status, state.email, state.code).then(response => {
    //       commit('SET_TOKEN', response.data.token)
    //       setToken(response.data.token)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          commit('SET_REFRESH_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_INITMENU', [])
          commit('SET_NAME', '')
          commit('SET_AVATAR', '')
          commit('SET_INTRODUCTION', '')
          removeStore('user.menus')
          removeToken()
          removeRefreshToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 初始化标识
    InitMenu({ commit }, menus) {
      return new Promise(resolve => {
        console.log('=====SET_INITMENU======')
        console.log(menus)
        commit('SET_INITMENU', menus)
        resolve()
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_REFRESH_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_INITMENU', [])
        commit('SET_NAME', '')
        commit('SET_AVATAR', '')
        commit('SET_INTRODUCTION', '')
        removeStore('user.menus')
        removeToken()
        removeRefreshToken()
        resolve()
      })
    },
    // 刷新token
    RefreshToken({ commit }, data) {
      return new Promise(resolve => {
        const { access_token, refresh_token } = data
        commit('SET_TOKEN', access_token)
        commit('SET_REFRESH_TOKEN', refresh_token)
        resolve()
      })
    },
    // 动态修改权限
    ChangeRoles({ commit, dispatch }) {
      return new Promise(resolve => {
        // commit('SET_TOKEN', role)
        // setToken(role)
        getUserInfo().then(response => {
          const result = response.data
          const roles = result.data.roles
          const permissions = result.data.permissions
          commit('SET_ROLES', roles)
          commit('SET_PERMISSIONS', permissions)
          commit('SET_NAME', result.data.name)
          commit('SET_AVATAR', result.data.avatar)
          commit('SET_INTRODUCTION', result.data.introduction)
          const routesData = { roles, permissions }
          dispatch('GenerateRoutes', routesData) // 动态修改权限后 重绘侧边菜单
          resolve()
        })
      })
    }
  }
}

export default user
